package com.zondy.mapgis.android.frag;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;

import android.annotation.SuppressLint;
import android.content.Context;
import android.graphics.Color;
import android.graphics.PointF;
import android.os.Bundle;
import android.os.Parcel;
import android.os.Parcelable;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.Spinner;
import android.widget.TextView;

import com.zondy.mapgis.android.activity.MapActivity;
import com.zondy.mapgis.android.base.BaseFragment;
import com.zondy.mapgis.android.graphic.Graphic;
import com.zondy.mapgis.android.graphic.GraphicMultiPoint;
import com.zondy.mapgis.android.graphic.GraphicPolygon;
import com.zondy.mapgis.android.graphic.GraphicsOverlay;
import com.zondy.mapgis.android.map.dao.IBaseLayer;
import com.zondy.mapgis.android.map.dao.ICallBack;
import com.zondy.mapgis.android.map.dao.IListener;
import com.zondy.mapgis.android.mapview.MapView;
import com.zondy.mapgis.android.mapview.MapView.MapViewTapListener;
import com.zondy.mapgis.android.model.EnumViewPos;
import com.zondy.mapgis.android.utils.DialogUtil;
import com.zondy.mapgis.android.utils.ToolToast;
import com.zondy.mapgis.android.view.Panel;
import com.zondy.mapgis.android.view.Panel.OnPanelListener;
import com.zondy.mapgis.core.featureservice.FeaturePagedResult;
import com.zondy.mapgis.core.geometry.Dot;
import com.zondy.mapgis.core.map.GroupLayer;
import com.zondy.mapgis.core.map.MapLayer;
import com.zondy.mapgis.explorer.MapApplication;
import com.zondy.mapgis.map.model.DataCenter;
import com.zondy.mapgis.map.model.Layer;
import com.zondy.mapgis.map.model.QueryCondition;
import com.zondy.mapgis.explorer.R;

@SuppressLint("ParcelCreator")
public class SearchModuleFragBK extends BaseFragment implements OnClickListener,MapViewTapListener,Serializable,Parcelable
{
	private static final long serialVersionUID = 1L;
	private String TAG = this.getClass().getSimpleName();
	private MapActivity mMapActivity = null;
	private MapView mMapView = null;
	private List<Dot> dotsLst = new ArrayList<Dot>();
	private List<Dot> dotsRectLst = new ArrayList<Dot>();

	private GraphicsOverlay mGraphicLayer = null;
	private GraphicPolygon mGraphicPolygon = null;
	private GraphicMultiPoint mGraphicMultiPoint = null;

	private Panel mPanel = null;
	private TextView mTitleTxt = null;
	private ImageView mRedoBtn = null;
	private RadioGroup mRadioGroup = null;
	private RadioButton mRadioFullBtn = null;
	private Spinner spSelLayer;
	public EditText mStrWhereEt = null;
	private Button mTopSearchBtn = null;

	private ArrayList<IBaseLayer> groupLayerList = new ArrayList<IBaseLayer>();
	/**
	 * 第一层是组图层的位置，第二层是该组图层下的子图层
	 */
	private ArrayList<ArrayList<IBaseLayer>> childLayerList = new ArrayList<ArrayList<IBaseLayer>>();

	private GroupLayer groupLayerForUnGrouped = null;
	private boolean hasUnGrouped = false;
	private ArrayAdapter<String> lyerNameAdapter = null;
	private List<String> nameLst = new ArrayList<String>();
	// 当前选择的矢量图层
	private IBaseLayer mChooseVtLyer = null;
	// 查询条件
	private QueryCondition mQueryCondition = new QueryCondition();
	private DataCenter mDataCenter = DataCenter.getInstance();
	// 空间查询范围点坐标
	private Dot[] dots = null;

	@Override
	public int bindLayout()
	{
		return R.layout.slidingdraw_search_module;
	}
	
	@Override
	public void onCreate(Bundle savedInstanceState)
	{
		super.onCreate(savedInstanceState);
		Log.d(TAG, "BaseFragment-->onCreate()");
		if (savedInstanceState != null) {
			//后台自动销毁，保存的数据
			ToolToast.showShort("savedInstanceState != null");
			}
	}

	@Override
	public void initView(View view)
	{
		mPanel = (Panel) view.findViewById(R.id.bottomPanel);
		mTitleTxt = (TextView) view.findViewById(R.id.title_text);
		mRedoBtn = (ImageView) view.findViewById(R.id.redo_btn);
		mRadioGroup = (RadioGroup) view.findViewById(R.id.radioGroup);
		mRadioFullBtn = (RadioButton) view.findViewById(R.id.full_range_rb);
		mRadioFullBtn.setChecked(true);
		spSelLayer = (Spinner) view.findViewById(R.id.sp_layer);
		mStrWhereEt = (EditText) view.findViewById(R.id.et_strwhere);
		mTopSearchBtn = (Button) view.findViewById(R.id.top_search_btn);

		view.findViewById(R.id.title_back).setOnClickListener(this);
		view.findViewById(R.id.attrs_edit_btn).setOnClickListener(this);
		view.findViewById(R.id.search_btn).setOnClickListener(this);
		view.findViewById(R.id.attrs_edit_layout).setOnClickListener(this);
		mTopSearchBtn.setOnClickListener(this);
		mRedoBtn.setOnClickListener(this);

		// SlideDrawer上滑与下滑监听
//		mSearchSlideDrawer.setOnDrawerOpenListener(new onDrawerOpen());
//		mSearchSlideDrawer.setOnDrawerCloseListener(new onDrawerClose());
		mPanel.setOpen(true, false);
		mPanel.setOnPanelListener(new OnPanelListener()
		{
			@Override
			public void onPanelOpened(Panel panel)
			{
				mTopSearchBtn.setVisibility(View.GONE);
			}
			
			@Override
			public void onPanelClosed(Panel panel)
			{
				mTopSearchBtn.setVisibility(View.VISIBLE);
			}
		});

	}

	@Override
	public void onClick(View v)
	{
		switch (v.getId())
		{
		case R.id.attrs_edit_btn:
			showEditAttrConFrag();
			mQueryCondition.setStrWhere("");
			break;
		case R.id.attrs_edit_layout:
			showEditAttrConFrag();
			mQueryCondition.setStrWhere("");
			break;
		case R.id.search_btn:
			doSearch();
			break;
		case R.id.top_search_btn:
			doSearch();
			break;
		case R.id.title_back:
			mMapActivity.removeFragment(TAG, null);
			mMapActivity.mMapBottomContent.setVisibility(View.VISIBLE);
			break;
		case R.id.redo_btn:
			mGraphicPolygon.removeAllPoints();
			mGraphicMultiPoint.removeAllPoints();

			// test
			for (int i = 0; i < dotsLst.size(); i++)
			{
				Log.d(TAG, "dotsLst.get(0).x:" + dotsLst.get(0).x + "y:" + dotsLst.get(0).y);
				Log.d(TAG, "dotsLst.get(1).x:" + dotsLst.get(1).x + "y:" + dotsLst.get(1).y);
			}
			List<Graphic> graphicLst = mGraphicLayer.getAllGraphics();
			for (int i = 0; i < graphicLst.size(); i++)
			{
				Log.d(TAG, "graphicLst[i]:" + graphicLst.get(i));
			}
			dotsLst.clear();
			dotsRectLst.clear();
			mMapView.setTapListener(this);
			mMapView.refresh();
			break;
		default:
			break;
		}

	}

	@SuppressLint("ResourceAsColor")
	@Override
	public void doBusiness(Context mContext)
	{
		mMapActivity = MapApplication.getApp().getMapActivity();
		mMapView = mMapActivity.mMapView;
		mMapView.setTapListener(this);

		mGraphicLayer = mMapView.getGraphicsOverlay();

		if (mGraphicPolygon == null)
		{
			mGraphicPolygon = new GraphicPolygon();
			mGraphicPolygon.setColor(R.color.lightskyblue);
		}

		if (mGraphicMultiPoint == null)
		{
			mGraphicMultiPoint = new GraphicMultiPoint();
			mGraphicMultiPoint.setColor(Color.BLUE);
			mGraphicMultiPoint.setPointSize(6);
		}
		// 添加Graphic
		mGraphicLayer.addGraphic(mGraphicMultiPoint);
		mGraphicLayer.addGraphic(mGraphicPolygon);
		// 获取所有图层
		int rootLayerCount = mMapView.getMap().getLayerCount();
		ArrayList<IBaseLayer> childLayerListForUnGrouped = new ArrayList<IBaseLayer>();

		for (int rootLayerIndex = 0; rootLayerIndex < rootLayerCount; rootLayerIndex++)
		{
			MapLayer rootMapLayer = mMapView.getMap().getLayer(rootLayerIndex);
			IBaseLayer rootLayer = new Layer(rootMapLayer);
			if (rootLayer.isGroupLayer())
			{
				this.groupLayerList.add(rootLayer);
				this.childLayerList.add(rootLayer.getChildLayers());
			}
			else
			{
				hasUnGrouped = true;
				childLayerListForUnGrouped.add(rootLayer);
			}
		}
		if (hasUnGrouped)
		{
			this.groupLayerForUnGrouped = new GroupLayer();
			this.groupLayerForUnGrouped.setName("未分组");

			IBaseLayer groupLayer = new Layer(this.groupLayerForUnGrouped);
			this.groupLayerList.add(0, groupLayer);
			this.childLayerList.add(0, childLayerListForUnGrouped);
		}

		// 为下拉列表定义一个适配器
		nameLst = getAllLayerName(getAllLayers());
		lyerNameAdapter = new ArrayAdapter<String>(getContext(), android.R.layout.simple_spinner_item, nameLst);
		lyerNameAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
		spSelLayer.setAdapter(lyerNameAdapter);
		spSelLayer.setSelection(0);
		// 点击选择图层
		spSelLayer.setOnItemSelectedListener(new OnItemSelectedListener()
		{
			@Override
			public void onItemSelected(AdapterView<?> parent, View view, int position, long id)
			{
				String strName = nameLst.get(position);
				mChooseVtLyer = getLayerByName(strName);
				mChooseVtLyer.setVisible(true);
			}

			@Override
			public void onNothingSelected(AdapterView<?> arg0)
			{

			}
		});
	}

	@Override
	public void mapViewTap(PointF viewPoint)
	{
		int select = mRadioGroup.getCheckedRadioButtonId();
		// 矩形绘制
		if (select == R.id.rect_range_rb)
		{
			mTitleTxt.setText("请选择矩形左上角点");
			Dot tapDot = mMapView.viewPointToMapPoint(viewPoint);
			dotsLst.add(tapDot);
			mGraphicMultiPoint.setPoints(dotsLst);
			// 绘制第二个点
			if (dotsLst.size() == 1)
			{
				mTitleTxt.setText("请选择矩形右上角点");
			}

			if (dotsLst.size() == 2)
			{
				mRedoBtn.setVisibility(View.VISIBLE);
				mTitleTxt.setText("");

				Dot dot1 = dotsLst.get(0);
				Dot dot2 = dotsLst.get(1);
				dotsRectLst.add(dot1);
				dotsRectLst.add(new Dot(dot1.x, dot2.y));
				dotsRectLst.add(dot2);
				dotsRectLst.add(new Dot(dot2.x, dot1.y));
				dotsRectLst.add(dot1);

				mMapActivity.mMapView.setTapListener(null);
				mGraphicPolygon.setPoints(dotsRectLst);
			}
			mMapView.refresh();
		}
		// 多边形绘制
		if (select == R.id.polygon_range_rb)
		{
			mTitleTxt.setText("请选择多边形边界点");
			if (dotsLst.size() > 3)
			{
				mGraphicPolygon.removePoint(mGraphicPolygon.getPointCount() - 1);
				dotsLst.remove(dotsLst.size() - 1);
			}

			Dot tapDot = mMapView.viewPointToMapPoint(viewPoint);
			dotsLst.add(tapDot);
			mGraphicMultiPoint.setPoints(dotsLst);
			if (dotsLst.size() > 2)
			{
				mRedoBtn.setVisibility(View.VISIBLE);
				// 绘制区前让区闭合
				dotsLst.add(dotsLst.get(0));
				mGraphicPolygon.setPoints(dotsLst);
			}
			mMapView.refresh();
		}
	}

	/*
	 * 开始查询
	 */
	public void doSearch()
	{
		int select = mRadioGroup.getCheckedRadioButtonId();
		if (select == R.id.rect_range_rb && dotsRectLst.size() > 0)
		{
			dots = new Dot[dotsRectLst.size()];
			for (int i = 0; i < dotsRectLst.size(); i++)
			{
				dots[i] = dotsRectLst.get(i);
				Log.d(TAG, "dots[i]===" + i + ":" + dots[i]);
			}
		}
		if (select == R.id.polygon_range_rb && dotsLst.size() > 0)
		{
			dots = new Dot[dotsLst.size()];
			for (int i = 0; i < dotsLst.size(); i++)
			{
				dots[i] = dotsLst.get(i);
				Log.d(TAG, "dots[i]===" + i + ":" + dots[i]);
			}
		}

		// 设置查询条件
		if (!mChooseVtLyer.isVectorLayer())
		{
			ToolToast.showShort("请选择矢量图层");
			return;
		}

		mQueryCondition.setLayer(mChooseVtLyer);
		if (dots != null && dots.length > 0)
		{
			mQueryCondition.setDots(dots);
		}
		// 查询对话框
		mMapActivity.runOnUiThread(new Runnable()
		{
			@Override
			public void run()
			{
				DialogUtil.showProgressDlg(mMapActivity, "正在查询...");
			}
		});
		
		mDataCenter.init();
//		mSearchSlideDrawer.close();//不能放到子线程去关闭
		mPanel.setOpen(false, false);
		mDataCenter.showAttMultiSearch(mMapActivity, mQueryCondition ,new IListener<FeaturePagedResult>()
		{
			@Override
			public void onCall(FeaturePagedResult result)
			{
				SearchResultFrag searchResultFrag = new SearchResultFrag();
				Bundle data = new Bundle();
				data.putSerializable("FeaturePagedResult", result);
				searchResultFrag.setArguments(data);
				mMapActivity.addFragment(EnumViewPos.FULL, searchResultFrag, searchResultFrag.getName(), null);
				mMapActivity.addFragBackListen(searchResultFrag);
				DialogUtil.hidenProgressDlg();
			}
		});

	}

	/**
	 * 显示编辑属性条件Frag
	 */
	public void showEditAttrConFrag()
	{
		if (mChooseVtLyer.isVectorLayer())
		{
			EditAttrConditionsFrag editAttrConFrag = new EditAttrConditionsFrag();
			Bundle data = new Bundle();
			data.putSerializable("layer", (Serializable) mChooseVtLyer);
			data.putSerializable("querycondition", mQueryCondition);
			data.putSerializable("SearchModuleFrag", this);
			editAttrConFrag.setArguments(data);
			mMapActivity.addFragment(EnumViewPos.FULL, editAttrConFrag, editAttrConFrag.getName(), new ICallBack()
			{
				@Override
				public void onCall(String str)
				{
					mStrWhereEt.setText(mQueryCondition.getStrWhere());
				}
			});
			mMapActivity.addFragBackListen(editAttrConFrag);
		}
		else
		{
			ToolToast.showShort("请选择矢量图层");
		}
	}

	/**
	 * 根据名字获取当前矢量图层
	 * 
	 * @param strName
	 * @return
	 */
	public IBaseLayer getLayerByName(String strName)
	{
		ArrayList<IBaseLayer> allLayers = new ArrayList<IBaseLayer>();

		allLayers = getAllLayers();
		for (int i = 0; i < allLayers.size(); i++)
		{
			if (allLayers.get(i).getName().equalsIgnoreCase(strName))
			{
				mChooseVtLyer = allLayers.get(i);
			}

		}

		return mChooseVtLyer;
	}

	/**
	 * 获取所有的图层名（str）
	 * 
	 * @param lst
	 * @return
	 */
	public List<String> getAllLayerName(ArrayList<IBaseLayer> lst)
	{
		for (int i = 0; i < lst.size(); i++)
		{
			nameLst.add(lst.get(i).getName());
		}

		return nameLst;
	}

	/**
	 * 取所有图层，不分组。
	 * 
	 * @return
	 */
	public ArrayList<IBaseLayer> getAllLayers()
	{
		if (isGrouped())
		{
			ArrayList<IBaseLayer> layersAll = new ArrayList<IBaseLayer>();
			for (IBaseLayer grpLyr : groupLayerList)
			{
				layersAll.addAll(grpLyr.getChildLayers());
			}
			return layersAll;
		}
		else
		{
			return childLayerList.get(0);
		}
	}

	/**
	 * 地图的图层是否分组了
	 * 
	 * @return
	 */
	public boolean isGrouped()
	{
		if (hasUnGrouped && groupLayerList.size() == 1)
		{
			return false;
		}
		return true;
	}

	@Override
	public void onDestroyView()
	{
		goback();
		super.onDestroyView();
	}

	@Override
	public boolean goback()
	{
		mMapView.setTapListener(null);
//		mGraphicLayer.removeAllGraphics();
		mGraphicLayer.removeGraphic(mGraphicMultiPoint);
		mGraphicLayer.removeGraphic(mGraphicPolygon);
		mMapView.refresh();
		return false;
	}

	@Override
	public boolean isLocked()
	{
		return false;
	}

	@Override
	public String getName()
	{
		return TAG;
	}

	@Override
	public int describeContents()
	{
		return 0;
	}

	@Override
	public void writeToParcel(Parcel arg0, int arg1)
	{

	}

}
